package com.itheima.web.controller.pms;

import com.itheima.service.pms.ProductAttributeService;
import com.itheima.utils.PageResult;
import com.itheima.utils.ResultData;
import com.itheima.vo.pms.PmsProductAttribute;
import com.itheima.vo.pms.ProductAttributeDto;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/productAttribute")
public class ProductAttributeController {

    @DubboReference
    public ProductAttributeService categoryService;

    /**
     *根据分类查询属性列表或参数列表
     */
    @GetMapping("list/{cid}")
    public ResultData list(@PathVariable Integer cid, Integer pageNum, Integer pageSize, Integer type) {

        if (pageNum!=null && pageSize!=null) {
            pageNum = (pageNum - 1) * pageSize;

            long count = categoryService.count();

            List<PmsProductAttribute> list = categoryService.pageInfo(pageNum, pageSize, cid, type);

            PageResult init = PageResult.init(count, (long) pageSize, (long) pageNum, list);

            return ResultData.ok("操作成功", init);
        }

        List<PmsProductAttribute> list = categoryService.pageInfoBy(cid, type);

        return ResultData.ok("操作成功",list);
    }

    /**
     *根据商品分类的id获取商品属性及属性分类
     */
    @GetMapping("/attrInfo/{productCategoryId}")
    public ResultData attrInfo(@PathVariable Integer productCategoryId){
        List<ProductAttributeDto> list=categoryService.selectByProductCategoryId(productCategoryId);
        return ResultData.ok("查询成功",list);
    }

    /**
     * 添加商品属性信息
     */
    @PostMapping("/create")
    public ResultData create(@RequestBody PmsProductAttribute productAttribute){
        //直接添加数据
        categoryService.save(productAttribute);
        return ResultData.ok("操作成功",null);
    }

    /**
     * 批量删除商品属性
     */
    @PostMapping("delete")
    @Transactional
    public ResultData delete(@RequestParam List<Integer> ids){
        for (Integer id : ids) {
            boolean b = categoryService.removeById(id);

            if (!b){
                return ResultData.error("操作失败");
            }

        }
        return ResultData.ok("操作成功",null);
    }

    /**
     * 修改商品属性信息
     */
    @PostMapping("/update/{id}")
    public ResultData create(@PathVariable Integer id,@RequestBody PmsProductAttribute productAttribute){
        productAttribute.setId(id);

        //直接添加数据
        boolean save = categoryService.updateById(productAttribute);

        if (!save){
            return ResultData.error("操作失败");
        }

        return ResultData.ok("操作成功",null);
    }

    /**
     * 查询单个商品属性
     */
    @GetMapping("{id}")
    public ResultData getById(@PathVariable Integer id){
        PmsProductAttribute byId = categoryService.getById(id);
        return ResultData.ok("",byId);
    }

}
